<template>
  <div class="uploadExcel-container">
    <div class="upload-container">
      <el-upload
        class="upload-demo upload-excel"
        drag
        action="/"
        accept=".xlsx, .xls"
        :before-upload="beforeUploadAction"
        :show-file-list="false"
        >
        <div class="el-upload__text">拖拽上传或<em>点击上传excel文件</em></div>
      </el-upload>
    </div>
    <div class="excel-content-container">
      <div class="excel-name-container">
        <el-tabs
          class="tab-name-container"
          v-model="activeName"
          type="card"
          @tab-click="tabClick"
          @tab-remove="removeTab"
        >
          <el-tab-pane
            v-for="(item,index) in excelFileList"
            :key="item.uid"
            :label="item.name"
            :index="index"
            :name="item.uid.toString()"
            :closable="true"
          >
            <template #label>
              {{ item.name }}
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="excel-content-table">
        <el-table
          :data="tableData"
          border
          highlight-current-row
          style="width: 100%; margin-top: 20px"
          :header-cell-style="{background: variables.tableHeaderBackGroundColor, color: variables.tableHeaderColor}"
        >
          <el-table-column v-for="item of tableHeader" :prop="item" :label="item" :key="item">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import ExcelJS from 'exceljs'
import variables from '@/styles/variables.scss'
export default {
  name: 'index',
  data(){
    return{
      tableData: [],
      tableHeader: [],
      activeName: '',
      excelFileList: [],
      activeUid: '',
    }
  },
  computed:{
    variables(){
      return variables
    },
  },
  methods:{
    beforeUploadAction (file) {
      this.excelFileList.push(file)
      if(this.excelFileList.findIndex(f => f.name === file.name) != this.excelFileList.findLastIndex(f => f.name === file.name)){
        this.$message.warning(file.name + ' 文件已存在')
        this.excelFileList.pop()
        return false
      }
      this.activeName = file.uid.toString()
      this.activeUid = file.uid
      this.readerExcelFile(file)
    },
    // 读excel文件
    readerExcelFile(file){
      return new Promise((resolve, reject) =>{
        const reader = new FileReader()
        reader.onload = async (e) =>{
          const data = e.target.result
          const workbook = new ExcelJS.Workbook()
          try{
            let res = await workbook.xlsx.load(data)
            const sheets = res._worksheets && res.worksheets.filter(item => typeof item != 'undefined')
            const table = []
            let headers = []
            sheets.forEach(sheet =>{
              sheet._rows.forEach((row, index) =>{
                if(index === 0){
                  row.values.forEach(it =>{
                    headers.push(it)
                  })
                }else{
                  let obj = {}
                  let arr = []
                  row.values.forEach(it =>{
                    arr.push(it)
                  })
                  headers.forEach((ite, i) =>{
                    obj[ite] = arr[i]
                  })
                  table.push(obj)
                }
              })
            })
            this.tableData = table
            this.tableHeader = headers
          }
          catch (e){
            this.$message.error('解析失败')
          }
        }
        reader.readAsArrayBuffer(file)
      })
    },
    // 切换tab页
    tabClick(tab){
      console.log(tab)
      const toUid= tab.name
      if(!this.isActive(toUid)){
        let file = {}
        file = this.excelFileList[Number(tab.index)]
        this.activeUid = file.uid
        this.activeName = file.uid.toString()
        this.readerExcelFile(file)
      }
    },
    // 移除tab标签
    async removeTab(activeTab){
      let index = this.excelFileList.findIndex(item => item.uid == activeTab)
      const nextFile= this.excelFileList[index + 1] || this.excelFileList[index - 1]
      this.excelFileList.splice(index,1)
      if(!nextFile){
        this.tableData = []
        this.tableHeader = []
        this.activeName = ''
        this.activeUid = ''
      }else{
        this.activeName = nextFile.uid.toString()
        this.activeUid = nextFile.uid
        this.readerExcelFile(nextFile)
      }
    },
    // 判断该tab页是否为当前显示的tab页
    isActive(toUid) {
      return toUid === this.activeUid
    },
  }
}
</script>

<style lang="scss" scoped>
.uploadExcel-container{
  background-color: white;
  padding: 20px;
  box-shadow: 0 0 12px rgba(0, 0,0 , 0.05);
  min-height: calc(100vh - 180px);
}
.upload-container{
  height: 60px;
  width: 100%;
  border: 1px solid #cde2f0;
  background: linear-gradient(to right, #fafeff, #fff, #fafeff)
}
.excel-content-container{
  width: 100%;
  min-height: calc(100vh - 290px);
  border-left: 1px solid #cde2f0;
  border-right: 1px solid #cde2f0;
  border-bottom: 1px solid #cde2f0;
  margin-top: 50px;
}
.excel-name-container{
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #cde2f0;
}
</style>
<style lang="scss">
.upload-excel{
  height: 60px;
  .el-upload-dragger{
    height: 60px;
    border: none;
    line-height: 60px;
  }
}
.tab-name-container{
  margin: 10px;
  .el-tabs__header{
    border: none;
    margin: 0 !important;
  }
  .el-tabs__nav{
    border: none !important;
  }
  .el-tabs__item{
    margin: 0 20px 0 0;
    height: 30px;
    line-height: 30px;
    border: 1px solid #62afe3 !important;
    border-radius: 4px;
  }
  .el-tabs__item.is-active{
    background: #78a6c4;
    color: white;
  }
  .el-tabs__nav-prev{
    top: -5px;
  }
  .el-tabs__nav-next{
    top: -5px;
  }
 }
.excel-content-table{
  .el-table{
    .el-table__empty-block{
      height: calc(100vh - 350px) !important;
    }
  }
}
</style>
